const user = require("../model/mangerUser");
const path = require("path");
const { base64ToFile, delFile } = require("../untils/untils");

/**
 * @api {POST} /createUser 创建用户
 * @apiName 创建用户
 * @apiGroup 用户管理
 * @apiVersion  1.0.0
 * 
 * @apiParam {Array} address 地址数组
 * @apiParam {string} email 邮箱
 * @apiParam {string} phone 手机号
 * @apiParam {string/base64} avatar 头像
 * @apiParam {string} password 密码
 * @apiParam {string} userName 用户名
 * @apiParam {string} roleName 角色名
 * @apiParam {string} detailAddress 详细地址
 * @apiParam {string} currentAuthority 当前权限角色
 * 
 * @apiSuccess (200) {Array} address 地址数组
 * @apiSuccess (200) {string} _id 用户id
 * @apiSuccess (200) {string} email 邮箱
 * @apiSuccess (200) {string} phone 手机号
 * @apiSuccess (200) {string} userName 用户名
 * @apiSuccess (200) {string} roleName 角色名
 * @apiSuccess (200) {string} detailAddress 详细地址
 * 
 * @apiParamExample  {type} 请求示例:
  address: ["北京市", "市辖区", "西城区"]
  avatar: "
  detailAddress: "北京南"
  email: "8474354495@qq.com"
  password: "admin2"
  phone: "15734182982"
  roleName: "user"
  userName: "托尔斯泰"
 * 
 * @apiSuccessExample {type} 返回示例:
 {
    "success": true,
    "data": {
        "address": [
            "天津市",
            "市辖区",
            "河东区"
        ],
        "type": "account",
        "_id": "60efcecc34001d0336b0828b",
        "email": "84744495@qq.com",
        "phone": 15757182985,
        "avatar": [
          {
            name: "avatar_1626940010564.png"
            status: "done"
            uid: "avatar_1626940010564"
            url: "http://localhost:3001/upload/avatar_1626940010564.png"
          }
        ],
        "userName": "c c2",
        "roleName": "user",
        "detailAddress": "s",
        "currentAuthority": "user",
        "registerTime": "2021-07-15T05:59:40.059Z",
        "__v": 0
    },
    "message": "添加用户成功",
    "code": 0
}
*/
const user_create = async (ctx, next) => {
  const {
    email,
    phone,
    avatar,
    userName,
    password,
    roleName,
    address,
    detailAddress,
  } = ctx.request.body;
  try {
    const findUserName = await user.findOne({ userName });
    const findEmail = await user.findOne({ email });
    const findPhone = await user.findOne({ phone });
    if (findUserName) {
      ctx.body = {
        message: "用户名存在",
        code: -1,
      };
    } else if (findEmail) {
      ctx.body = {
        message: "邮箱存在",
        code: -1,
      };
    } else if (findPhone) {
      ctx.body = {
        message: "手机号存在",
        code: -1,
      };
    } else {
      const fileName = `avatar_${new Date().getTime()}`;
      // 头像传过来则上传为文件，切用url储存
      const res = avatar
        ? base64ToFile(
            avatar,
            path.resolve(__dirname, `../public/upload/${fileName}.png`)
          )
        : false;
      const createUser = await user.create({
        email,
        phone,
        avatar: res
          ? [
              {
                uid: fileName,
                name: `${fileName}.png`,
                status: "done",
                url: `${ctx.origin}/upload/${fileName}.png`,
              },
            ]
          : "",
        userName,
        password,
        roleName,
        address: address ? address : "",
        detailAddress: detailAddress ? detailAddress : "",
        currentAuthority: roleName,
      });
      if (createUser !== null) {
        ctx.body = {
          message: "添加用户成功",
          code: 0,
        };
      } else {
        ctx.body = {
          message: "添加用户失败",
          code: -1,
        };
      }
    }
  } catch (error) {
    ctx.body = {
      message: "添加用户失败：" + error,
      code: -1,
    };
  }
};
/**
 * @api {POST} /removeUser 删除用户
 * @apiName 删除用户
 * @apiGroup 用户管理
 * @apiVersion  1.0.0
 * 
 * @apiParam {string} userName 用户名
 * 
 * 
 * @apiSuccessExample {type} 返回示例:
 {
    success: true,
    message: "删除成功",
    code: 0,
  }
*/
const user_remove = async (ctx, next) => {
  const { userName } = ctx.request.body;
  try {
    const removeUser = await user.remove({ userName });
    if (removeUser.deletedCount >= 1) {
      ctx.body = {
        success: true,
        message: "删除成功",
        code: 0,
      };
    } else {
      ctx.body = {
        success: false,
        message: "删除失败",
        code: -1,
      };
    }
  } catch (error) {
    ctx.body = {
      success: false,
      message: "删除用户失败：" + error,
      code: -1,
    };
  }
};
/**
 * @api {POST} /updateUser 用户更新
 * @apiName 用户更新
 * @apiGroup 用户管理
 * @apiVersion  1.0.0
 * 
 * @apiParam {Array} address 地址数组
 * @apiParam {string} _id 用户id
 * @apiParam {string} email 邮箱
 * @apiParam {string} phone 手机号
 * @apiParam {string} userName 用户名
 * @apiParam {string} roleName 角色名
 * @apiParam {string} detailAddress 详细地址
 * @apiParam {string} currentAuthority 当前权限角色
 * 
 * @apiSuccess (200) {Array} address 地址数组
 * @apiSuccess (200) {string} _id 用户id
 * @apiSuccess (200) {string} email 邮箱
 * @apiSuccess (200) {string} phone 手机号
 * @apiSuccess (200) {string} userName 用户名
 * @apiSuccess (200) {string} roleName 角色名
 * @apiSuccess (200) {string} detailAddress 详细地址
 * @apiSuccess (200) {string} currentAuthority 当前权限角色
 * 
 * @apiSuccessExample {type} 返回示例:
 {
    "success": true,
    "data": {
        "address": [
            "天津市",
            "市辖区",
            "河东区"
        ],
        "type": "account",
        "_id": "60efcecc34001d0336b0828b",
        "email": "84744495@qq.com",
        "phone": 15757182985,
        "avatar": [
          {
            name: "avatar_1626940010564.png"
            status: "done"
            uid: "avatar_1626940010564"
            url: "http://localhost:3001/upload/avatar_1626940010564.png"
          }
        ],
        "userName": "c c2",
        "roleName": "user",
        "detailAddress": "s",
        "currentAuthority": "user",
        "registerTime": "2021-07-15T05:59:40.059Z",
        "__v": 0
    },
    "message": "查询用户成功",
    "code": 0
}
*/
const user_update = async (ctx, next) => {
  try {
    const {
      _id,
      userName,
      email,
      phone,
      avatar,
      roleName,
      address,
      detailAddress,
    } = ctx.request.body;
    const findUser = await user.findOne({ userName, _id: { $ne: _id } });
    const findEmail = await user.findOne({ email, _id: { $ne: _id } });
    const findPhone = await user.findOne({ phone, _id: { $ne: _id } });
    if (findUser) {
      ctx.body = {
        data: null,
        message: "用户名重复",
        code: -1,
      };
    } else if (findEmail) {
      ctx.body = {
        data: null,
        message: "邮箱重复",
        code: -1,
      };
    } else if (findPhone) {
      ctx.body = {
        data: null,
        message: "手机号重复",
        code: -1,
      };
    } else {
      let upAvatar = "";
      const userFind = await user.findById(_id);
      if (userFind && userFind.avatar?.[0]?.uid === avatar?.[0]?.uid && userFind.avatar) {
        upAvatar = avatar;
      } else {
        const fileName = `avatar_${new Date().getTime()}`;
        const removeAndUp = () => {
          const dirPath = path.join(__dirname, "..", "public/upload");
          if (userFind.avatar && userFind.avatar?.[0]?.name) {
            delFile(dirPath, userFind.avatar?.[0]?.name);
          }
          base64ToFile(
            avatar,
            path.resolve(__dirname, `../public/upload/${fileName}.png`)
          );
          return true
        };
        // 头像传过来则上传为文件，切用url储存
        const res = avatar ? removeAndUp() : false;
        upAvatar = res
          ? [
              {
                uid: fileName,
                name: `${fileName}.png`,
                status: "done",
                url: `${ctx.origin}/upload/${fileName}.png`,
              },
            ]
          : "";
      }

      const updateUser = await user.findByIdAndUpdate(_id, {
        userName,
        email,
        phone,
        avatar: upAvatar,
        roleName,
        address,
        detailAddress,
      });
      if (updateUser) {
        ctx.body = {
          data: updateUser,
          message: "用户更新成功",
          code: 0,
        };
      } else {
        ctx.body = {
          data: null,
          message: "用户更新失败",
          code: -1,
        };
      }
    }
  } catch (error) {
    ctx.body = {
      message: "更新用户失败：" + error,
      code: -1,
    };
  }
};
/**
 * @api {get} /findUser 用户列表查询
 * @apiName 用户列表查询
 * @apiGroup 用户管理
 * @apiVersion  1.0.0
 * 
 * @apiSuccess (200) {Array} address 地址数组
 * @apiSuccess (200) {string} _id 用户id
 * @apiSuccess (200) {string} email 邮箱
 * @apiSuccess (200) {string} phone 手机号
 * @apiSuccess (200) {string} userName 用户名
 * @apiSuccess (200) {string} roleName 角色名
 * @apiSuccess (200) {string} detailAddress 详细地址
 * @apiSuccess (200) {string} currentAuthority 当前权限角色
 * 
 * @apiSuccessExample {type} 返回示例:
 {
    "success": true,
    "data": {
        "address": [
            "天津市",
            "市辖区",
            "河东区"
        ],
        "type": "account",
        "_id": "60efcecc34001d0336b0828b",
        "email": "84744495@qq.com",
        "phone": 15757182985,
        "avatar": [
          {
            name: "avatar_1626940010564.png"
            status: "done"
            uid: "avatar_1626940010564"
            url: "http://localhost:3001/upload/avatar_1626940010564.png"
          }
        ],
        "userName": "c c2",
        "roleName": "user",
        "detailAddress": "s",
        "currentAuthority": "user",
        "registerTime": "2021-07-15T05:59:40.059Z",
        "__v": 0
    },
    "message": "查询用户成功",
    "code": 0
}
*/
const user_find = async (ctx, next) => {
  try {
    const {
      _id,
      userName,
      email,
      phone,
      avatar,
      roleName,
      address,
      detailAddress,
    } = ctx.request.body;
    const findUser = await user.find({}, { password: 0 });
    if (findUser.length > 0) {
      ctx.body = {
        success: true,
        data: findUser,
        message: "查询用户列表成功",
        code: 0,
      };
    } else {
      tx.body = {
        success: false,
        data: null,
        message: "没有用户",
        code: -1,
      };
    }
  } catch (error) {
    ctx.body = {
      success: false,
      message: "查询用户失败：" + error,
      code: -1,
    };
  }
};
/**
 * @api {get} /currentUser 当前用户查询
 * @apiName 当前用户查询
 * @apiGroup 用户管理
 * @apiVersion  1.0.0
 * 
 * @apiParam {String} _id 用户id
 * 
 * @apiSuccess (200) {Array} address 地址数组
 * @apiSuccess (200) {string} _id 用户id
 * @apiSuccess (200) {string} email 邮箱
 * @apiSuccess (200) {string} phone 手机号
 * @apiSuccess (200) {string} userName 用户名
 * @apiSuccess (200) {string} roleName 角色名
 * @apiSuccess (200) {string} detailAddress 详细地址
 * @apiSuccess (200) {string} currentAuthority 当前权限角色
 * 
 * @apiSuccessExample {type} 返回示例:
 {
    "success": true,
    "data": {
        "address": [
            "天津市",
            "市辖区",
            "河东区"
        ],
        "type": "account",
        "_id": "60efcecc34001d0336b0828b",
        "email": "84744495@qq.com",
        "phone": 15757182985,
        "avatar": "",
        "userName": "c c2",
        "roleName": "user",
        "detailAddress": "s",
        "currentAuthority": "user",
        "registerTime": "2021-07-15T05:59:40.059Z",
        "__v": 0
    },
    "message": "查询用户成功",
    "code": 0
}
*/
const current_user_find = async (ctx, next) => {
  try {
    const { _id } = ctx.request.query;
    if (_id === "0") {
      ctx.body = {
        success: true,
        data: {
          userName: "admin",
          avatar: '',
          name: '管理员',
          userid: _id,
        },
        message: "当前为管理员",
        code: 0,
      };
    } else {
      const findUser = await user.findById(_id, { password: 0 });
      if (findUser) {
        ctx.body = {
          success: true,
          data: findUser,
          message: "查询用户成功",
          code: 0,
        };
      } else {
        tx.body = {
          success: false,
          data: null,
          message: "查询用户失败",
          code: -1,
        };
      }
    }
  } catch (error) {
    ctx.body = {
      success: false,
      message: "查询用户失败：" + error,
      code: -1,
    };
  }
};

module.exports = {
  "POST /createUser": user_create,
  "POST /removeUser": user_remove,
  "POST /updateUser": user_update,
  "GET /findUser": user_find,
  "GET /currentUser": current_user_find,
};
